package com.dragon.logical.service.auth.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import com.dragon.logical.service.auth.MenuService;
import com.dragon.repository.entity.AdminDepartment;
import com.dragon.repository.entity.Menu;
import com.dragon.repository.entity.RoleMenu;
import com.dragon.repository.mapper.MenuMapper;
import com.dragon.repository.mapper.RoleMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-06-12
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {


    @Autowired
    MenuMapper mapper;

    @Autowired
    RoleMenuMapper roleMenuMapper;


    @Override
    public List<Menu> selectMenuList(){
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(Menu::getSort);
        List<Menu> menus = mapper.selectList(queryWrapper);
        return  menus;
    }

    @Override
    public Integer add(Menu menu){
        menu.setCreateTime(DateUtil.date());
        mapper.insert(menu);
        return menu.getId();
    }
    @Override
    public void modify(Menu menu){
        Menu menu1 = mapper.selectById(menu.getId());
        if(menu1 == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        menu.setUpdateTime(DateUtil.date());
        mapper.updateById(menu);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void delete(Integer id){
        Menu menu1 = mapper.selectById(id);
        if(menu1 == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        mapper.deleteById(id);

        //删除中间表的数据
        roleMenuMapper.delete(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getMenuId,id));
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void delete(List<Integer> ids){
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(Menu::getId,ids);
        List<Menu> menuList = mapper.selectList(queryWrapper);
        if(ids.size()!=menuList.size()){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }

        //角色菜单表
        QueryWrapper<RoleMenu> rmQueryWrapper = new QueryWrapper<>();
        rmQueryWrapper.lambda().in(RoleMenu::getMenuId,ids);
        roleMenuMapper.delete(rmQueryWrapper);
        mapper.delete(queryWrapper);
    }



}
